<?php
class NoTranslation extends ArgError {
	public function __construct($page, $mod)
	{
		parent::__construct();
		$this->library = 'Translator';
		$this->type = 'Library';
		$this->generalError = true;
		$this->message = 'No translation page ' . $page . ' in module ' . $mod;
	}
}

class translator {
	
	private $mod;
	private $Translations;
	private $lang;
	
	public function __construct($mod = null) {
		if ($mod == null)
			$mod = LastClass();
		$this->mod = $mod;
		$this->lang = $this->_FindLang();
		if (!in_array('en', $this->lang))
			array_push($this->lang, 'en');
		$this->Translations = array();
	}
	
	public function setLang($lang)
	{
		array_unshift($this->lang, $lang);
	}
	
	public function get($word)
	{
		if (isset($this->Translations[$word]))
		{
			return $this->Translations[$word];
		}
		else
			return null;
	}
	
	public function load($page, $mod = null)
	{
		if ($mod === null)
			$mod = $this->mod;
			
		$basedir = MODSDIR . core_modules::modDir($mod) . DIRECTORY_SEPARATOR
			. 'lang' . DIRECTORY_SEPARATOR;
		foreach ($this->lang as $lang)
		{
			$file = $basedir . $lang . DIRECTORY_SEPARATOR . $page . '.lng';
			if (file_exists($file))
			{
				$this->Translations = array_merge($this->Translations, parse_ini_file($file));
				return;
			}
		}
		throw new NoTranslation($page, $mod);
	}
	
	public function apply(template &$tpl)
	{
		foreach ($this->Translations as $key => $translate)
			$tpl->assign('LNG_'.$key, $translate);
	}
	
	private function _FindLang()
	{
		$locate = strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]);
		$locate = explode(',', $locate);
		$result = array();
		
		foreach ($locate as $lang)
		{
			$lang = explode(';', $lang);
			if (!isset($lang[1]))
				$lang[1] = 1;
			$result[$lang[0]] = $lang[1];
		}
		
		asort($result);
		return array_keys($result);
	}
}
